package com.manlitech.manlichat.base.redis;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.manlitech.manlichat.base.exception.MyException;
import com.manlitech.manlichat.enums.ResultEnums;
import io.lettuce.core.ReadFrom;
import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * redis集群配置
 * @author shensg
 * @date 2019/3/21
 */
@Configuration
public class RedisConfiguration {

    @Autowired
    private RedisProperties redisProperties;

    @Value("${redis.maxRedirects:3}")
    private int maxRedirects;

    @Value("${redis.refreshTime:5}")
    private int refreshTime;

    @Bean
    public LettuceConnectionFactory redisConnectionFactory() {
    	//单机版
    	if(redisProperties.getCluster() == null) {
    		RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
    		redisStandaloneConfiguration.setDatabase(redisProperties.getDatabase());
    		redisStandaloneConfiguration.setHostName(redisProperties.getHost());
    		redisStandaloneConfiguration.setPassword(redisProperties.getPassword());
    		redisStandaloneConfiguration.setPort(redisProperties.getPort());
    		return new LettuceConnectionFactory(redisStandaloneConfiguration);
    	}
    	//集群版本
    	if(redisProperties.getCluster() != null) {
    		RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(redisProperties.getCluster().getNodes());
    		redisClusterConfiguration.setMaxRedirects(maxRedirects);
    		//支持自适应集群拓扑刷新和静态刷新源
            ClusterTopologyRefreshOptions clusterTopologyRefreshOptions =  ClusterTopologyRefreshOptions.builder()
                    .enablePeriodicRefresh()
                    .enableAllAdaptiveRefreshTriggers()
                    .refreshPeriod(Duration.ofSeconds(refreshTime))
                    .build();
            ClusterClientOptions clusterClientOptions = ClusterClientOptions.builder()
                    .topologyRefreshOptions(clusterTopologyRefreshOptions).build();
          //从优先，读写分离，读从可能存在不一致，最终一致性CP
            LettuceClientConfiguration lettuceClientConfiguration = LettuceClientConfiguration.builder()
                    .readFrom(ReadFrom.SLAVE_PREFERRED)
                    .clientOptions(clusterClientOptions).build();
            
            return new LettuceConnectionFactory(redisClusterConfiguration, lettuceClientConfiguration);
    	}
    	throw new MyException(ResultEnums.UNKONW_REDIS_TYPE);
        
    }



    @Bean
    public RedisTemplate<Object, Object> redisTemplate(LettuceConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);       
        ObjectMapper om = new ObjectMapper();
        
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(DateTime.class,new JodaDateTimeJsonSerializer());
        simpleModule.addDeserializer(DateTime.class,new JodaDateTimeJsonDeserializer());
        om.registerModule(simpleModule);
        om.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

}
